<?php
/**
 * WordPress Spider Monitor - 高级安全授权模块
 * 
 * 此模块提供服务器端付费功能验证，防止客户端绕过授权
 * 所有付费功能必须通过此模块验证才能访问
 */

if (!defined('ABSPATH')) {
    exit;
}

class WP_Spider_Premium_Security {
    
    private static $instance = null;
    private $encryption_key;
    private $feature_permissions = array();
    
    /**
     * 获取单例实例
     */
    public static function get_instance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    /**
     * 构造函数
     */
    private function __construct() {
        $this->encryption_key = $this->get_encryption_key();
        $this->init_feature_permissions();
    }
    
    /**
     * 获取加密密钥
     */
    private function get_encryption_key() {
        $key = get_option('wp_spider_encryption_key');
        if (!$key) {
            $key = wp_generate_password(64, true, true);
            update_option('wp_spider_encryption_key', $key);
        }
        return $key;
    }
    
    /**
     * 初始化功能权限配置
     */
    private function init_feature_permissions() {
        $this->feature_permissions = array(
            // 时间范围限制
            'time_range_week' => array(
                'name' => '7天数据查看',
                'description' => '查看最近7天的蜘蛛访问数据',
                'premium_required' => true,
                'encrypted_check' => 'time_range_week_check'
            ),
            'time_range_month' => array(
                'name' => '30天数据查看',
                'description' => '查看最近30天的蜘蛛访问数据',
                'premium_required' => true,
                'encrypted_check' => 'time_range_month_check'
            ),
            
            // 功能模块限制
            'trend_chart' => array(
                'name' => '趋势图表',
                'description' => '访问趋势图表功能',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'top_spiders' => array(
                'name' => 'Top蜘蛛统计',
                'description' => '查看Top蜘蛛排行榜',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'access_paths' => array(
                'name' => '访问路径分析',
                'description' => '分析蜘蛛访问路径',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'article_crawl' => array(
                'name' => '文章爬取分析',
                'description' => '分析文章爬取情况',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'ip_segments' => array(
                'name' => 'IP段分析',
                'description' => '分析蜘蛛IP段分布',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'path_stats' => array(
                'name' => '路径统计',
                'description' => '统计访问路径数据',
                'premium_required' => false,
                'time_dependent' => true
            ),
            'article_stats' => array(
                'name' => '文章统计',
                'description' => '统计文章访问数据',
                'premium_required' => false,
                'time_dependent' => true
            )
        );
    }
    
    /**
     * 验证付费功能访问权限
     * 
     * @param string $feature 功能名称
     * @param string $period 时间范围 (today, yesterday, week, month)
     * @param array $context 额外上下文信息
     * @return array 验证结果
     */
    public function verify_premium_access($feature, $period = 'today', $context = array()) {
        // 生成请求指纹，防止重放攻击
        $request_fingerprint = $this->generate_request_fingerprint($feature, $period, $context);
        
        // 检查功能是否存在
        if (!isset($this->feature_permissions[$feature])) {
            return $this->create_denied_response('未知功能', '功能不存在');
        }
        
        $feature_config = $this->feature_permissions[$feature];
        
        // 检查是否为付费功能
        if ($feature_config['premium_required']) {
            if (!$this->is_premium_activated()) {
                return $this->create_denied_response(
                    $feature_config['name'],
                    $feature_config['description'] . '需要激活PRO版本'
                );
            }
        }
        
        // 检查时间依赖功能
        if (isset($feature_config['time_dependent']) && $feature_config['time_dependent']) {
            if (in_array($period, array('week', 'month'))) {
                if (!$this->is_premium_activated()) {
                    return $this->create_denied_response(
                        $feature_config['name'],
                        '7天和30天' . $feature_config['description'] . '需要激活PRO版本'
                    );
                }
            }
        }
        
        // 生成访问令牌
        $access_token = $this->generate_access_token($feature, $period, $request_fingerprint);
        
        return $this->create_granted_response($feature, $access_token, $request_fingerprint);
    }
    
    /**
     * 验证客户端请求
     * 
     * @param string $token 访问令牌
     * @param string $feature 功能名称
     * @param string $period 时间范围
     * @return bool 验证结果
     */
    public function validate_client_request($token, $feature, $period) {
        try {
            $decoded_token = $this->decode_access_token($token);
            
            // 检查令牌是否过期 (5分钟有效期)
            if (time() - $decoded_token['timestamp'] > 300) {
                return false;
            }
            
            // 检查功能匹配
            if ($decoded_token['feature'] !== $feature) {
                return false;
            }
            
            // 检查时间范围匹配
            if ($decoded_token['period'] !== $period) {
                return false;
            }
            
            // 检查请求指纹
            $current_fingerprint = $this->generate_request_fingerprint($feature, $period);
            if ($decoded_token['fingerprint'] !== $current_fingerprint) {
                return false;
            }
            
            return true;
            
        } catch (Exception $e) {
            error_log('[SpiderMonitor] Token validation error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 生成安全响应
     * 
     * @param bool $is_authorized 是否授权
     * @param string $feature 功能名称
     * @param string $period 时间范围
     * @return array 安全响应
     */
    public function generate_secure_response($is_authorized, $feature, $period) {
        $response = array(
            'is_premium' => $is_authorized,
            'feature' => $feature,
            'period' => $period,
            'timestamp' => time(),
            'security_hash' => $this->generate_security_hash($feature, $period, $is_authorized)
        );
        
        if (!$is_authorized) {
            $feature_config = $this->feature_permissions[$feature] ?? array();
            $response['premium_message'] = $this->get_premium_message($feature, $period);
            $response['upgrade_url'] = admin_url('admin.php?page=spider-license');
            $response['data'] = array();
        }
        
        return $response;
    }
    
    /**
     * 检查是否已激活PRO版本
     */
    public function is_premium_activated() {
        // 首先检查本地状态，避免频繁的远程请求
        $encrypted_status = get_option('wp_spider_premium_status_encrypted');
        if ($encrypted_status) {
            try {
                $decrypted_status = $this->decrypt_data($encrypted_status);
                $status_data = json_decode($decrypted_status, true);
                
                // 如果本地状态明确为false，直接返回false
                if ($status_data && isset($status_data['is_active']) && $status_data['is_active'] === false) {
                    return false;
                }
            } catch (Exception $e) {
                // 解密失败，继续检查远程状态
            }
        }
        
        // 使用订阅客户端检查远程状态
        if (isset($GLOBALS['spider_subscription_client'])) {
            $client = $GLOBALS['spider_subscription_client'];
            $remote_status = $client->is_activated();
            
            // 如果远程状态为true，同步到本地
            if ($remote_status) {
                $license_info = $client->get_license_info();
                if ($license_info && $license_info['success']) {
                    $this->set_premium_status(true, $license_info['expires_at'] ?? null);
                    return true;
                }
            } else {
                // 如果远程状态为false，清除本地状态
                $this->set_premium_status(false, null);
                return false;
            }
        }
        
        // 备用：使用加密的方式检查本地授权状态
        $encrypted_status = get_option('wp_spider_premium_status_encrypted');
        if (!$encrypted_status) {
            return false;
        }
        
        try {
            $decrypted_status = $this->decrypt_data($encrypted_status);
            $status_data = json_decode($decrypted_status, true);
            
            // 检查授权是否有效
            if (!$status_data || !isset($status_data['is_active'])) {
                return false;
            }
            
            // 检查是否过期
            if (isset($status_data['expires_at']) && time() > $status_data['expires_at']) {
                return false;
            }
            
            // 检查域名是否匹配
            if (isset($status_data['domain']) && $status_data['domain'] !== $this->get_current_domain()) {
                return false;
            }
            
            return $status_data['is_active'] === true;
            
        } catch (Exception $e) {
            error_log('[SpiderMonitor] Premium status check error: ' . $e->getMessage());
            return false;
        }
    }
    
    /**
     * 生成请求指纹
     */
    private function generate_request_fingerprint($feature, $period, $context = array()) {
        $data = array(
            'feature' => $feature,
            'period' => $period,
            'user_id' => get_current_user_id(),
            'ip' => $this->get_client_ip(),
            'user_agent' => substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 100),
            'timestamp' => time(),
            'context' => $context
        );
        
        return hash('sha256', serialize($data) . $this->encryption_key);
    }
    
    /**
     * 生成访问令牌
     */
    private function generate_access_token($feature, $period, $fingerprint) {
        $token_data = array(
            'feature' => $feature,
            'period' => $period,
            'fingerprint' => $fingerprint,
            'timestamp' => time(),
            'user_id' => get_current_user_id()
        );
        
        return $this->encrypt_data(json_encode($token_data));
    }
    
    /**
     * 解码访问令牌
     */
    private function decode_access_token($token) {
        $decrypted = $this->decrypt_data($token);
        return json_decode($decrypted, true);
    }
    
    /**
     * 生成安全哈希
     */
    private function generate_security_hash($feature, $period, $is_authorized) {
        $data = array(
            'feature' => $feature,
            'period' => $period,
            'is_authorized' => $is_authorized,
            'timestamp' => time(),
            'key' => $this->encryption_key
        );
        
        return hash('sha256', serialize($data));
    }
    
    /**
     * 创建拒绝响应
     */
    private function create_denied_response($feature_name, $message) {
        return array(
            'is_premium' => false,
            'feature' => $feature_name,
            'premium_message' => $message,
            'upgrade_url' => admin_url('admin.php?page=spider-license'),
            'data' => array(),
            'security_hash' => $this->generate_security_hash($feature_name, '', false)
        );
    }
    
    /**
     * 创建授权响应
     */
    private function create_granted_response($feature, $access_token, $fingerprint) {
        return array(
            'is_premium' => true,
            'feature' => $feature,
            'access_token' => $access_token,
            'fingerprint' => $fingerprint,
            'security_hash' => $this->generate_security_hash($feature, '', true)
        );
    }
    
    /**
     * 获取付费提示信息
     */
    private function get_premium_message($feature, $period) {
        $feature_config = $this->feature_permissions[$feature] ?? array();
        $feature_name = $feature_config['name'] ?? $feature;
        
        if (in_array($period, array('week', 'month'))) {
            return "7天和30天{$feature_name}需要激活PRO版本";
        }
        
        return "{$feature_name}需要激活PRO版本";
    }
    
    /**
     * 加密数据
     */
    private function encrypt_data($data) {
        $iv = openssl_random_pseudo_bytes(16);
        $encrypted = openssl_encrypt($data, 'AES-256-CBC', $this->encryption_key, 0, $iv);
        return base64_encode($iv . $encrypted);
    }
    
    /**
     * 解密数据
     */
    private function decrypt_data($encrypted_data) {
        $data = base64_decode($encrypted_data);
        $iv = substr($data, 0, 16);
        $encrypted = substr($data, 16);
        return openssl_decrypt($encrypted, 'AES-256-CBC', $this->encryption_key, 0, $iv);
    }
    
    /**
     * 安全地获取授权信息（只返回必要的公开信息）
     */
    public function get_license_info() {
        $encrypted_status = get_option('wp_spider_premium_status_encrypted');
        if (!$encrypted_status) {
            return array(
                'is_active' => false,
                'expires_at' => null,
                'activated_at' => null,
                'domain' => $this->get_current_domain()
            );
        }
        
        try {
            $decrypted = $this->decrypt_data($encrypted_status);
            $status_data = json_decode($decrypted, true);
            
            if (!$status_data) {
                return array(
                    'is_active' => false,
                    'expires_at' => null,
                    'activated_at' => null,
                    'domain' => $this->get_current_domain()
                );
            }
            
            // 只返回安全的公开信息
            return array(
                'is_active' => $status_data['is_active'] ?? false,
                'expires_at' => $status_data['expires_at'] ?? null,
                'activated_at' => $status_data['activated_at'] ?? null,
                'domain' => $status_data['domain'] ?? $this->get_current_domain()
            );
        } catch (Exception $e) {
            return array(
                'is_active' => false,
                'expires_at' => null,
                'activated_at' => null,
                'domain' => $this->get_current_domain()
            );
        }
    }
    
    /**
     * 获取当前域名
     */
    private function get_current_domain() {
        return parse_url(home_url(), PHP_URL_HOST);
    }
    
    /**
     * 获取客户端IP
     */
    private function get_client_ip() {
        $ip_keys = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
        foreach ($ip_keys as $key) {
            if (array_key_exists($key, $_SERVER) === true) {
                foreach (explode(',', $_SERVER[$key]) as $ip) {
                    $ip = trim($ip);
                    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) !== false) {
                        return $ip;
                    }
                }
            }
        }
        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
    }
    
    /**
     * 设置PRO授权状态
     */
    public function set_premium_status($is_active, $expires_at = null) {
        $status_data = array(
            'is_active' => $is_active,
            'expires_at' => $expires_at,
            'domain' => $this->get_current_domain(),
            'activated_at' => time()
        );
        
        $encrypted_status = $this->encrypt_data(json_encode($status_data));
        update_option('wp_spider_premium_status_encrypted', $encrypted_status);
    }
    
    /**
     * 获取功能权限配置
     */
    public function get_feature_permissions() {
        return $this->feature_permissions;
    }
}

/**
 * 获取安全模块实例
 */
function wp_spider_premium_security() {
    return WP_Spider_Premium_Security::get_instance();
}

/**
 * 验证付费功能访问权限的便捷函数
 */
function wp_spider_verify_premium_access($feature, $period = 'today', $context = array()) {
    $security = wp_spider_premium_security();
    return $security->verify_premium_access($feature, $period, $context);
}

/**
 * 生成安全响应的便捷函数
 */
function wp_spider_generate_secure_response($is_authorized, $feature, $period) {
    $security = wp_spider_premium_security();
    return $security->generate_secure_response($is_authorized, $feature, $period);
}
